package com.zhuoan.im.server.handler;

import com.zhuoan.im.server.command.ImStatus;
import com.zhuoan.im.webapp.biz.GroupsBiz;
import com.zhuoan.im.webapp.dao.model.reqbody.GroupBody;
import com.zhuoan.im.webapp.dao.model.respbody.CreateGroupRespBody;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImPacket;
import org.jim.common.packets.Command;
import org.jim.common.packets.Group;
import org.jim.common.packets.RespBody;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbCmdHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;

/**
 * FriendsListReqHandler
 *
 * @author weixiang.wu
 * @date 2018-10-17 19:51
 **/
@RestController
public class InnerGroupMemberHandler extends AbCmdHandler {

    private final static Logger logger = LoggerFactory.getLogger(InnerGroupMemberHandler.class);

    @Resource
    private GroupsBiz groupsBiz;


    @Override
    public Command command() {
        return Command.addAndGet(com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_REQ.getResMessage(), com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_REQ.getResCode());
    }

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {

        // 1.判断是否已经登录
        String creatorUserId = channelContext.getUserid();
        if (creatorUserId == null) {
            return new ImPacket(Command.addAndGet(com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResMessage(),
                com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResCode()), JsonKit.toJsonBytes("请您先登录"));
        }

        // 2.必要参数校验
        GroupBody groupBody = JsonKit.toBean(packet.getBody(), GroupBody.class);
        if (StringUtils.isBlank(String.valueOf(groupBody.getGroupId()))
            || StringUtils.isBlank(groupBody.getTargetId())
            || StringUtils.isBlank(groupBody.getType())
        ) {
            return new ImPacket(Command.addAndGet(com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResMessage(),
                com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResCode()), JsonKit.toJsonBytes("请选择群聊的用户"));
        }
        // 3.新增/删除组内人员
        logger.info("用户id=[" + creatorUserId + "]开始创建群组");
        groupBody.setCreatorUserId(creatorUserId);
        groupsBiz.operateGroupMember(groupBody);

        // 4.返回群组信息
        RespBody respBody = new CreateGroupRespBody(
            Command.addAndGet(com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResMessage(),
                com.zhuoan.im.server.command.Command.INNER_GROUP_MEMBER_RES.getResCode())
            , ImStatus.C10026);

        return new ImPacket(respBody.toByte());
    }
}
